<template>
  <div class="space-war-container">
    <div class="game-area" ref="gameBoard" tabindex="0" @keydown="handleKeydown" @keyup="handleKeyup">
      <!-- 游戏主画面 -->
      <div class="game-screen" :class="{ 'game-over': gameOver }">
        <!-- 玩家飞船 -->
        <div class="player-ship" :style="playerStyle" :class="{ 'hit': isPlayerHit }">
          <div class="ship-body"></div>
          <div class="engine-flame"></div>
        </div>

        <!-- 子弹 -->
        <div v-for="bullet in bullets" 
             :key="bullet.id" 
             class="bullet"
             :style="{ left: bullet.x + 'px', top: bullet.y + 'px' }">
        </div>

        <!-- 敌人 -->
        <div v-for="enemy in enemies" 
             :key="enemy.id" 
             class="enemy-ship"
             :class="enemy.type"
             :style="{ left: enemy.x + 'px', top: enemy.y + 'px' }">
        </div>

        <!-- 爆炸效果 -->
        <div v-for="explosion in explosions" 
             :key="explosion.id" 
             class="explosion"
             :style="{ left: explosion.x + 'px', top: explosion.y + 'px' }">
        </div>

        <!-- 能量护盾 -->
        <div v-if="isShieldActive" 
             class="shield"
             :style="playerStyle">
        </div>
      </div>

      <!-- 游戏信息面板 -->
      <div class="game-panel">
        <div class="game-stats">
          <div class="stat-item">
            <span class="stat-label">得分</span>
            <span class="stat-value">{{ score }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">生命值</span>
            <div class="health-bar">
              <div class="health-fill" :style="{ width: `${health}%` }"></div>
            </div>
          </div>
          <div class="stat-item">
            <span class="stat-label">能量</span>
            <div class="energy-bar">
              <div class="energy-fill" :style="{ width: `${energy}%` }"></div>
            </div>
          </div>
        </div>

        <div class="weapon-panel">
          <button class="weapon-button" 
                  @click="activateShield"
                  :disabled="energy < 30 || isShieldActive">
            护盾 (30能量)
          </button>
          <button class="weapon-button" 
                  @click="fireMissile"
                  :disabled="energy < 50">
            导弹 (50能量)
          </button>
          <button class="weapon-button" 
                  @click="activateUltimate"
                  :disabled="energy < 100">
            终极技能 (100能量)
          </button>
        </div>

        <!-- 游戏控制 -->
        <div class="game-controls">
          <button class="control-button" @click="startGame" :disabled="isPlaying">
            开始游戏
          </button>
          <button class="control-button" @click="pauseGame" :disabled="!isPlaying">
            {{ isPaused ? '继续' : '暂停' }}
          </button>
        </div>

        <!-- 操作说明 -->
        <div class="game-instructions">
          <h3>操作说明</h3>
          <ul>
            <li>WASD / 方向键：移动飞船</li>
            <li>空格键：发射激光</li>
            <li>1/2/3：使用特殊武器</li>
            <li>P：暂停游戏</li>
          </ul>
        </div>
      </div>

      <!-- 游戏结束界面 -->
      <div v-if="gameOver" class="game-over-screen">
        <h2>游戏结束</h2>
        <p>最终得分: {{ score }}</p>
        <p>击落敌机: {{ killCount }}</p>
        <button class="restart-button" @click="restartGame">重新开始</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'

// 游戏配置
const GAME_WIDTH = 800
const GAME_HEIGHT = 600
const PLAYER_SPEED = 5
const BULLET_SPEED = 8
const ENEMY_SPEED = 2
const SPAWN_INTERVAL = 1000
const ENERGY_REGEN = 1

// 游戏状态
const score = ref(0)
const health = ref(100)
const energy = ref(100)
const isPlaying = ref(false)
const isPaused = ref(false)
const gameOver = ref(false)
const killCount = ref(0)
const isPlayerHit = ref(false)
const isShieldActive = ref(false)

// 游戏对象
const playerPos = ref({ x: GAME_WIDTH / 2, y: GAME_HEIGHT - 100 })
const bullets = ref([])
const enemies = ref([])
const explosions = ref([])

// 按键状态
const keys = ref({
  up: false,
  down: false,
  left: false,
  right: false,
  shoot: false
})

// 游戏循环
let gameLoop = null
let enemySpawnLoop = null
let shootLoop = null

// 计算玩家样式
const playerStyle = computed(() => ({
  left: `${playerPos.value.x}px`,
  top: `${playerPos.value.y}px`
}))

// 处理键盘输入
const handleKeydown = (event) => {
  if (!isPlaying.value || isPaused.value) return

  switch (event.code) {
    case 'ArrowUp':
    case 'KeyW':
      keys.value.up = true
      break
    case 'ArrowDown':
    case 'KeyS':
      keys.value.down = true
      break
    case 'ArrowLeft':
    case 'KeyA':
      keys.value.left = true
      break
    case 'ArrowRight':
    case 'KeyD':
      keys.value.right = true
      break
    case 'Space':
      event.preventDefault()
      keys.value.shoot = true
      break
    case 'Digit1':
      activateShield()
      break
    case 'Digit2':
      fireMissile()
      break
    case 'Digit3':
      activateUltimate()
      break
    case 'KeyP':
      pauseGame()
      break
  }
}

const handleKeyup = (event) => {
  switch (event.code) {
    case 'ArrowUp':
    case 'KeyW':
      keys.value.up = false
      break
    case 'ArrowDown':
    case 'KeyS':
      keys.value.down = false
      break
    case 'ArrowLeft':
    case 'KeyA':
      keys.value.left = false
      break
    case 'ArrowRight':
    case 'KeyD':
      keys.value.right = false
      break
    case 'Space':
      keys.value.shoot = false
      break
  }
}

// 更新玩家位置
const updatePlayer = () => {
  if (keys.value.up) {
    playerPos.value.y = Math.max(0, playerPos.value.y - PLAYER_SPEED)
  }
  if (keys.value.down) {
    playerPos.value.y = Math.min(GAME_HEIGHT - 50, playerPos.value.y + PLAYER_SPEED)
  }
  if (keys.value.left) {
    playerPos.value.x = Math.max(0, playerPos.value.x - PLAYER_SPEED)
  }
  if (keys.value.right) {
    playerPos.value.x = Math.min(GAME_WIDTH - 50, playerPos.value.x + PLAYER_SPEED)
  }
}

// 发射子弹
const shoot = () => {
  if (!keys.value.shoot || energy.value < 5) return
  
  energy.value -= 5
  bullets.value.push({
    id: Date.now(),
    x: playerPos.value.x + 22,
    y: playerPos.value.y,
    type: 'laser'
  })
}

// 生成敌人
const spawnEnemy = () => {
  const types = ['scout', 'fighter', 'bomber']
  const type = types[Math.floor(Math.random() * types.length)]
  
  enemies.value.push({
    id: Date.now(),
    type,
    x: Math.random() * (GAME_WIDTH - 40),
    y: -50,
    health: type === 'bomber' ? 3 : 1,
    speed: type === 'scout' ? ENEMY_SPEED * 1.5 : ENEMY_SPEED
  })
}

// 更新游戏状态
const updateGame = () => {
  if (!isPlaying.value || isPaused.value) return

  // 更新玩家
  updatePlayer()

  // 更新子弹
  bullets.value.forEach(bullet => {
    bullet.y -= BULLET_SPEED
  })
  bullets.value = bullets.value.filter(bullet => bullet.y > -10)

  // 更新敌人
  enemies.value.forEach(enemy => {
    enemy.y += enemy.speed
  })
  enemies.value = enemies.value.filter(enemy => enemy.y < GAME_HEIGHT + 50)

  // 检查碰撞
  checkCollisions()

  // 恢复能量
  if (energy.value < 100) {
    energy.value = Math.min(100, energy.value + ENERGY_REGEN)
  }

  // 移除过期的爆炸效果
  explosions.value = explosions.value.filter(exp => Date.now() - exp.time < 1000)
}

// 碰撞检测
const checkCollisions = () => {
  // 子弹击中敌人
  bullets.value.forEach(bullet => {
    enemies.value.forEach(enemy => {
      if (checkHit(bullet, enemy)) {
        enemy.health--
        if (enemy.health <= 0) {
          createExplosion(enemy.x, enemy.y)
          enemies.value = enemies.value.filter(e => e.id !== enemy.id)
          score.value += enemy.type === 'bomber' ? 30 : 10
          killCount.value++
        }
        bullets.value = bullets.value.filter(b => b.id !== bullet.id)
      }
    })
  })

  // 敌人撞击玩家
  if (!isShieldActive.value) {
    enemies.value.forEach(enemy => {
      if (checkHit(enemy, { x: playerPos.value.x, y: playerPos.value.y, width: 50, height: 50 })) {
        health.value -= enemy.type === 'bomber' ? 30 : 10
        createExplosion(enemy.x, enemy.y)
        enemies.value = enemies.value.filter(e => e.id !== enemy.id)
        showHitEffect()
        
        if (health.value <= 0) {
          endGame()
        }
      }
    })
  }
}

// 检查碰撞
const checkHit = (obj1, obj2) => {
  return obj1.x < obj2.x + 40 &&
         obj1.x + 6 > obj2.x &&
         obj1.y < obj2.y + 40 &&
         obj1.y + 6 > obj2.y
}

// 创建爆炸效果
const createExplosion = (x, y) => {
  explosions.value.push({
    id: Date.now(),
    x,
    y,
    time: Date.now()
  })
}

// 显示受击效果
const showHitEffect = () => {
  isPlayerHit.value = true
  setTimeout(() => {
    isPlayerHit.value = false
  }, 200)
}

// 特殊武器
const activateShield = () => {
  if (energy.value < 30 || isShieldActive.value) return
  
  energy.value -= 30
  isShieldActive.value = true
  setTimeout(() => {
    isShieldActive.value = false
  }, 5000)
}

const fireMissile = () => {
  if (energy.value < 50) return
  
  energy.value -= 50
  bullets.value.push({
    id: Date.now(),
    x: playerPos.value.x + 22,
    y: playerPos.value.y,
    type: 'missile'
  })
}

const activateUltimate = () => {
  if (energy.value < 100) return
  
  energy.value = 0
  enemies.value.forEach(enemy => {
    createExplosion(enemy.x, enemy.y)
  })
  enemies.value = []
  score.value += 100
}

// 游戏控制
const startGame = () => {
  if (isPlaying.value) return
  
  resetGame()
  isPlaying.value = true
  isPaused.value = false
  
  gameLoop = setInterval(updateGame, 1000 / 60)
  enemySpawnLoop = setInterval(spawnEnemy, SPAWN_INTERVAL)
  shootLoop = setInterval(shoot, 200)
}

const pauseGame = () => {
  if (!isPlaying.value) return
  isPaused.value = !isPaused.value
}

const endGame = () => {
  isPlaying.value = false
  gameOver.value = true
  clearInterval(gameLoop)
  clearInterval(enemySpawnLoop)
  clearInterval(shootLoop)
}

const resetGame = () => {
  score.value = 0
  health.value = 100
  energy.value = 100
  killCount.value = 0
  gameOver.value = false
  isShieldActive.value = false
  playerPos.value = { x: GAME_WIDTH / 2, y: GAME_HEIGHT - 100 }
  bullets.value = []
  enemies.value = []
  explosions.value = []
  keys.value = { up: false, down: false, left: false, right: false, shoot: false }
}

const restartGame = () => {
  resetGame()
  startGame()
}

// 生命周期钩子
onMounted(() => {
  window.addEventListener('keydown', handleKeydown)
  window.addEventListener('keyup', handleKeyup)
})

onUnmounted(() => {
  window.removeEventListener('keydown', handleKeydown)
  window.removeEventListener('keyup', handleKeyup)
  clearInterval(gameLoop)
  clearInterval(enemySpawnLoop)
  clearInterval(shootLoop)
})
</script>

<style scoped>
.space-war-container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: var(--theme-container-bg, #1a1a1a);
}

.game-area {
  width: 1000px;
  height: 600px;
  display: flex;
  gap: 20px;
  position: relative;
}

.game-screen {
  width: 800px;
  height: 600px;
  position: relative;
  background: radial-gradient(circle at center, #1a237e 0%, #0d1117 100%);
  overflow: hidden;
  border-radius: 12px;
}

.game-screen::before {
  content: '';
  position: absolute;
  width: 200%;
  height: 200%;
  top: -50%;
  left: -50%;
  background-image: 
    radial-gradient(2px 2px at 40px 60px, #ffffff 50%, rgba(0,0,0,0)),
    radial-gradient(2px 2px at 20px 50px, rgba(255,255,255,0.4) 50%, rgba(0,0,0,0)),
    radial-gradient(2px 2px at 30px 100px, rgba(255,255,255,0.2) 50%, rgba(0,0,0,0));
  background-size: 150px 150px;
  animation: starfield 5s linear infinite;
}

.player-ship {
  position: absolute;
  width: 50px;
  height: 50px;
  transform: translate(-50%, -50%);
  transition: all 0.1s;
}

.ship-body {
  position: absolute;
  width: 100%;
  height: 100%;
  background-color: #3b82f6;
  clip-path: polygon(50% 0%, 100% 100%, 50% 80%, 0% 100%);
  box-shadow: 0 0 10px rgba(59, 130, 246, 0.5);
}

.engine-flame {
  position: absolute;
  bottom: -10px;
  left: 50%;
  transform: translateX(-50%);
  width: 10px;
  height: 20px;
  background: linear-gradient(to bottom, #f59e0b, #ef4444);
  clip-path: polygon(50% 100%, 0% 0%, 100% 0%);
  animation: flame 0.1s infinite alternate;
}

.bullet {
  position: absolute;
  width: 6px;
  height: 20px;
  background-color: #60a5fa;
  border-radius: 3px;
  box-shadow: 0 0 5px #60a5fa;
}

.enemy-ship {
  position: absolute;
  width: 40px;
  height: 40px;
  transition: transform 0.2s;
}

.enemy-ship.scout {
  background-color: #ef4444;
  clip-path: polygon(50% 0%, 100% 100%, 50% 70%, 0% 100%);
}

.enemy-ship.fighter {
  background-color: #8b5cf6;
  clip-path: polygon(0% 0%, 100% 0%, 80% 100%, 20% 100%);
}

.enemy-ship.bomber {
  background-color: #f59e0b;
  clip-path: circle(50% at 50% 50%);
}

.explosion {
  position: absolute;
  width: 40px;
  height: 40px;
  background: radial-gradient(circle, #fbbf24 0%, #ef4444 50%, transparent 100%);
  border-radius: 50%;
  animation: explode 0.5s forwards;
}

.shield {
  position: absolute;
  width: 80px;
  height: 80px;
  background: radial-gradient(circle, rgba(147, 197, 253, 0.3) 0%, rgba(147, 197, 253, 0) 70%);
  border-radius: 50%;
  transform: translate(-50%, -50%);
  animation: shield-pulse 1s infinite;
}

.game-panel {
  width: 180px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.game-stats {
  background-color: rgba(0, 0, 0, 0.5);
  padding: 15px;
  border-radius: 8px;
}

.stat-item {
  margin-bottom: 10px;
}

.stat-label {
  display: block;
  color: #e2e8f0;
  margin-bottom: 5px;
}

.stat-value {
  color: #60a5fa;
  font-size: 24px;
  font-weight: bold;
}

.health-bar,
.energy-bar {
  height: 10px;
  background-color: #1f2937;
  border-radius: 5px;
  overflow: hidden;
}

.health-fill {
  height: 100%;
  background-color: #10b981;
  transition: width 0.3s;
}

.energy-fill {
  height: 100%;
  background-color: #3b82f6;
  transition: width 0.3s;
}

.weapon-panel {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.weapon-button {
  padding: 8px;
  background-color: #3b82f6;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
}

.weapon-button:disabled {
  background-color: #4b5563;
  cursor: not-allowed;
}

.game-over-screen {
  position: absolute;
  inset: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.8);
  color: white;
}

.restart-button {
  margin-top: 20px;
  padding: 10px 20px;
  background-color: #3b82f6;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

@keyframes starfield {
  from { transform: translateY(0); }
  to { transform: translateY(50%); }
}

@keyframes flame {
  from { height: 20px; }
  to { height: 25px; }
}

@keyframes explode {
  0% { transform: scale(0.5); opacity: 1; }
  100% { transform: scale(2); opacity: 0; }
}

@keyframes shield-pulse {
  0% { transform: translate(-50%, -50%) scale(1); opacity: 1; }
  50% { transform: translate(-50%, -50%) scale(1.1); opacity: 0.8; }
  100% { transform: translate(-50%, -50%) scale(1); opacity: 1; }
}

.player-ship.hit {
  animation: hit 0.2s;
}

@keyframes hit {
  0% { filter: brightness(1); }
  50% { filter: brightness(3); }
  100% { filter: brightness(1); }
}
</style> 